package com.biz.primus.app.erpbridge.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.biz.primus.base.enums.commodity.OssType;
import com.biz.primus.base.exception.BizBusinessException;
import com.biz.primus.common.utils.DateUtil;
import com.biz.primus.common.utils.StringUtil;
import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * OssService
 *
 * @author JKLiues
 * @date 2017年11月17日
 */
@Service
@Slf4j
public class OssService {

    //生成本地文件名称
    private static final String FILE_NAME_TIME_FMT = "yyyyMMddHH";

    @Value("${primus.oss.endpoint}")
    private String ossEndpoint;

    @Value("${primus.oss.access-key-id}")
    private String ossAccessKeyId;

    @Value("${primus.oss.access-key-secret}")
    private String ossAccessKeySecret;

    @Value("${primus.oss.local-directory}")
    private String ossStockLocalDir;

    @Autowired
    private List<OssFullDataHandler> ossFullDataHandlers;

    /**
     * 每天定时任务 初始化全量信息
     */
    public void handleOssFullData(MnsOssMessageVo mnsOssMessageVo) {
        if (mnsOssMessageVo == null) {
            log.warn("全量消息为空!");
            return;
        }
        OssType type = mnsOssMessageVo.getType();
        Timestamp startTime = DateUtil.now();
        log.info("开始重置全量{}. 开始时间: {}", type.getDescription(), startTime);
        Stopwatch stopwatchGlobal = Stopwatch.createStarted();
        File file = createLocalFile(type);
        if (file == null) {
            log.error("创建本地全量主数据文件失败!");
            return;
        }
        log.info("全量文件开始下载.......");
        long downloadUsedTime = downloadFile(mnsOssMessageVo, file);
        log.info("全量文件下载完成downloadUsedTime: {}", downloadUsedTime);

        if (!verifyMd5(mnsOssMessageVo.getMd5(), file)) {
            return;
        }

        OssFullDataHandler ossFullDataHandler = getOssFullDataHandleService(type);
        Timestamp finishedTime = DateUtil.now();
        ossFullDataHandler.process(file, type);
        long usedTime = stopwatchGlobal.elapsed(TimeUnit.MILLISECONDS);
        log.info("完成重置全量{}. 结束时间: {}, 用时: {} ms", type.getDescription(), finishedTime, usedTime);
    }

    /**
     * 根据类型获取对应处理service
     *
     * @param type
     * @return
     */
    private OssFullDataHandler getOssFullDataHandleService(OssType type) {
        for (OssFullDataHandler service : ossFullDataHandlers) {
            if (ArrayUtils.contains(service.getOssType(), type)) {
                return service;
            }
        }
        log.error("无法获取{}的处理器", type);
        throw new BizBusinessException(String.format("无法获取%s的处理器", type));
    }

    /**
     * 校验md5
     *
     * @param md5
     * @param file
     * @return
     */
    private boolean verifyMd5(String md5, File file) {
        String md5FromFile = null;
        try {
            md5FromFile = StringUtil.getMD5(file);
        } catch (IOException e) {
            log.error("获取本地{}文件md5异常", e);
        }
        if (Objects.equals(md5, md5FromFile)) {
            return true;
        }
        log.error("文件md5不匹配[oss md5 ==> local md5]: {} ==> {}", md5, md5FromFile);
        return false;
    }

    /**
     * 下载Oss文件
     *
     * @param mnsOssMessageVo
     * @param file
     * @return
     */
    private long downloadFile(MnsOssMessageVo mnsOssMessageVo, File file) {
        OSSClient ossClient = null;
        long downloadUsedTime = 0L;
        try {
            log.debug("开始下载Oss文件[{}]至本地文件[{}]. ", mnsOssMessageVo, file.getAbsolutePath());
            Stopwatch stopwatch = Stopwatch.createStarted();
            ossClient = new OSSClient(ossEndpoint, ossAccessKeyId, ossAccessKeySecret);
            ObjectMetadata object = ossClient.getObject(new GetObjectRequest(mnsOssMessageVo.getBucket(),
                    mnsOssMessageVo.getKey()), file);
            downloadUsedTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);
            log.debug("下载完成. 用时 {} ms", downloadUsedTime);
        } catch (Exception e) {
            log.error("下载异常.", e);
        } finally {
            // 关闭client
            if (ossClient != null){
                ossClient.shutdown();
            }
        }
        return downloadUsedTime;
    }

    /**
     * 创建本地全量文件
     *
     * @param type
     * @return
     */
    private File createLocalFile(OssType type) {
        File file = null;
        if (StringUtils.endsWith(ossStockLocalDir, "/")) {
            ossStockLocalDir = StringUtils.removeEnd(ossStockLocalDir, "/");
        }
        try {
            file = new File(ossStockLocalDir + File.separator + type.getName() + File.separator + DateUtil
                    .getNowFmtDatetime(FILE_NAME_TIME_FMT));
            log.debug("Oss本地文件[{}].", file.getAbsolutePath());
            File parent = file.getParentFile();
            if (parent != null && !parent.exists()) {
                log.debug("Oss本地文件目录不存在, 创建! [{}].", file.getAbsolutePath());
                parent.mkdirs();
            }
            if (!file.exists()) {
                log.debug("Oss本地文件不存在, 创建! [{}]", file.getAbsolutePath());
                file.createNewFile();
            }
        } catch (Exception e) {
            log.error("Oss本地文件创建异常!", e);
        }
        return file;
    }
}